package com.sky.loveshop.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/12/26 23:13
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String PREFIX = "daily_number:";
    private static final String START_NUMBER = "1000";

    /**
     * 生成每日订单序号 从1000开始依次递增1:1001,1002,1003,1004,1005......
     * @return
     */
    public String generatePlatformDayId() {
        String currentDate = getCurrentDate();
        String key = PREFIX + currentDate;

        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(value)) {
            redisTemplate.opsForValue().set(key, START_NUMBER);
            // 设置过期时间为1天（86400秒）
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            return START_NUMBER;
        } else {
            String i = String.valueOf(Integer.parseInt(value) + 1);
            redisTemplate.opsForValue().set(key, i);
            // 设置过期时间为1天（86400秒）
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
            return i;
        }
    }

    private String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }
}
